<template>
  <div>
     <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index" >
          <td> {{ index+1 }} </td>
          <td> {{ item.name }} </td>
          <td> {{ item.age }} </td>
          <td> {{ item.sex }} </td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="bj(index)">编辑</button>
          </td>
        </tr>
      </table>
      <h2>年龄总和:{{ sum }}</h2>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr:[],
      name:'',
      age:'',
      sex:''
    };
  },
  computed:{
    sum() {
      return this.arr.reduce((sum, val) => (sum += val.age), 0);
    },
  },
  methods: {
    add(){
      if (!this.name) return alert('请填写名字信息');
      if (!this.age) return alert('请填写年龄信息');
      if (!this.sex) return alert('请填写性别信息');
      if (sessionStorage.getItem('index')) {
        let index = sessionStorage.getItem('index');
        this.arr[index].name = this.name;
        this.arr[index].age = this.age;
        this.arr[index].gender = this.gender;
        sessionStorage.removeItem('index');
      }else{
        this.arr.push({name:this.name, age:this.age, sex:this.sex})
      }
      this.name='',
      this.age='',
      this.sex=''
    },
    del(index) {
      this.arr.splice(index, 1);
    },
    bj(index) {
      this.name = this.arr[index].name;
      this.age = this.arr[index].age;
      this.sex = this.arr[index].sex;
      sessionStorage.setItem('index', index); 
    },
  },
};
</script>
<style>
</style>
